<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getRoomListApi,
  addRoomApi,
  updateRoomApi,
  delRoomListApi,
  getRoomApi
} from '@/api/location/room/room'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElRow, ElCol, ElTag } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

defineOptions({
  name: 'LocationRoom'
})

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getRoomListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data || [],
      total: res.count || 0
    }
  },
  fetchDelApi: async (value) => {
    const res = await delRoomListApi(value as number[])
    return res.code === 200
  }
})

const { dataList, loading, total, pageSize, currentPage } = tableState
const { getList, delList } = tableMethods

// 房间类型标签渲染函数
const getRoomTypeTag = (type: string) => {
  const typeMap: Record<string, { type: string; label: string }> = {
    hospital: { type: 'success', label: '医院' },
    residential: { type: 'primary', label: '住宅' }
  }

  const typeInfo = typeMap[type] || { type: 'info', label: type }

  return <ElTag type={typeInfo.type}>{typeInfo.label}</ElTag>
}

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection',
    show: true,
    disabled: true
  },
  {
    field: 'id',
    label: '编号',
    show: true,
    disabled: false,
    align: 'center',
    headerAlign: 'center',
    width: '80px'
  },
  {
    field: 'name',
    label: '房间名称',
    show: true,
    disabled: false,
    minWidth: '120px'
  },
  {
    field: 'type',
    label: '房间类型',
    show: true,
    disabled: false,
    width: '100px',
    slots: {
      default: (data: any) => {
        return getRoomTypeTag(data.row.type)
      }
    }
  },
  {
    field: 'location',
    label: '位置',
    show: true,
    disabled: false,
    minWidth: '180px'
  },
  {
    field: 'update_datetime',
    label: '更新时间',
    show: false,
    width: '180px'
  },
  {
    field: 'create_datetime',
    label: '创建时间',
    width: '180px',
    show: true
  },
  {
    field: 'action',
    width: '150px',
    label: '操作',
    fixed: 'right',
    disabled: false,
    show: true,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" link size="small" onClick={() => editAction(row)}>
              编辑
            </BaseButton>
            <BaseButton
              type="danger"
              loading={delLoading.value}
              link
              size="small"
              onClick={() => delData(row)}
            >
              删除
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '房间名称',
    component: 'Input',
    componentProps: {
      clearable: true,
      style: {
        width: '180px'
      }
    }
  },
  {
    field: 'type',
    label: '房间类型',
    component: 'Select',
    componentProps: {
      clearable: true,
      options: [
        { label: '医院', value: 'hospital' },
        { label: '住宅', value: 'residential' }
      ],
      style: {
        width: '180px'
      }
    }
  },
  {
    field: 'location',
    label: '位置',
    component: 'Input',
    componentProps: {
      clearable: true,
      style: {
        width: '180px'
      }
    }
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  currentPage.value = 1
  searchParams.value = data
  getList()
}

const delLoading = ref(false)

const delData = async (row?: any) => {
  delLoading.value = true
  if (row) {
    await delList(true, [row.id]).finally(() => {
      delLoading.value = false
    })
  } else {
    await delList(true).finally(() => {
      delLoading.value = false
    })
  }
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref<'add' | 'edit'>('add')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const addAction = () => {
  dialogTitle.value = '添加房间'
  actionType.value = 'add'
  currentRow.value = undefined
  dialogVisible.value = true
}

const editAction = async (row: any) => {
  if (!row || !row.id) return

  dialogTitle.value = '编辑房间'
  actionType.value = 'edit'
  const res = await getRoomApi(row.id)
  // 确保ID被正确保存
  currentRow.value = { ...res.data, id: row.id }
  dialogVisible.value = true
}

const save = async () => {
  if (!writeRef.value) return

  const valid = await writeRef.value.validate()
  if (!valid) {
    ElMessage.warning('请完成必填项')
    return
  }

  saveLoading.value = true
  try {
    const formData = await writeRef.value.getFormData()

    if (formData) {
      let res
      if (actionType.value === 'add') {
        res = await addRoomApi(formData)
        if (res && res.code === 200) {
          ElMessage.success('添加成功')
          dialogVisible.value = false
          getList()
        }
      } else if (actionType.value === 'edit') {
        // 确保ID存在且有效
        if (formData.id && typeof formData.id === 'number') {
          res = await updateRoomApi(formData.id, formData)
          if (res && res.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            getList()
          }
        } else {
          ElMessage.error('更新失败：缺少有效的ID')
          return
        }
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      showAction
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
      @refresh="getList"
    >
      <template #toolbar>
        <ElRow :gutter="10">
          <ElCol :span="1.5">
            <BaseButton type="primary" @click="addAction">添加房间</BaseButton>
            <BaseButton type="danger" @click="delData(null)">批量删除</BaseButton>
          </ElCol>
        </ElRow>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write ref="writeRef" :current-row="currentRow" :action-type="actionType" />

    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
